const db = require('../../../db/index');
const myDate = require('../../tool/myDate');
const arrMethod = require('../../tool/arrMethod');
const addDepartment = require('./02addDepartment');

// 存入考勤表中
exports.addAttendanceSheet = () => {
	const sql = 'select * from user where state < 2';
	db.query(sql, (err, results) => {
		// 获取用户表需要的信息
		let arr = results.map((item) => {
			return Object.assign(
				{},
				{ user_id: item.id },
				{ department_id: item.id_department1},
				{ position_id: item.id_position}
			)
		})
		// 今天的日期
		let toDay = myDate.toDay();
		for(let i = 0 ; i < arr.length ; i++){
			Object.defineProperty(arr[i], 'day_date', {
				value: toDay,
				writable:true,
				enumerable:true,
				configurable:true
			})
		}
		// 去掉日期里，id和日期同时重复的部分
		const sql = 'select * from attendance';
		db.query(sql, (err, results)=>{
			let arrResults = results.map((item) => {
				return Object.assign(
					{},
					{ user_id: item.user_id },
					{ day_date: item.day_date }
				)
			})
			let repetitionArr = [];
			let newArr = [];
			let index = 0;
			// 删除重复的部分
			for(let i = 0 ; i < arr.length ; i++){
				for(let j = 0 ; j < arrResults.length ; j++){
					if(arr[i].user_id == arrResults[j].user_id && arr[i].day_date == arrResults[j].day_date){
						repetitionArr[index] = arr[i];
						index++
					}
				}
			};
			// 如果全部重复，则直接走第二步，存入考勤表
			if(repetitionArr.length === arr.length){
				console.log('考勤表已经满了', toDay);
				// 执行添加部门考勤表
				addDepartment.addDepartment(toDay);
				return
			}
			newArr = arrMethod.getDiffer(arr, repetitionArr);
			newArr = arrMethod.mysqlArr(newArr);
			const sql = "insert into attendance(user_id, department_id,  position_id, day_date) values ?";
			db.query(sql, [newArr], (err, results) => {
				console.log('存入考勤表成功', toDay);
				// 执行添加部门考勤表
				addDepartment.addDepartment(toDay);
			});
		})
	})
}